package top.lishuoboy.mysql.index.controller;

import cn.hutool.core.date.TimeInterval;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
import top.lishuoboy.dependency.base.db.MyDbUtil;
import top.lishuoboy.mysql.index.domain.Demo;
import top.lishuoboy.mysql.index.service.DemoService;

import javax.sql.DataSource;
import java.util.ArrayList;
import java.util.List;

@Slf4j
@RestController
public class IndexController {
    @Autowired
    DataSource ds;
    @Autowired
    DemoService demoService;

    @GetMapping("/saveBatchDemo/{count}")
    Object saveBatchDemo(@PathVariable int count) {
        TimeInterval timeInterval = new TimeInterval();

        List<Demo> demoList = new ArrayList(count);
        for (long i = 1; i <= count; i++) {

            Demo demo = Demo.builder()
                    .id(i).id2(i).id3(i).id4(i)
                    .build();
            demoList.add(demo);

            //持久化。count不要超过n万条，再大List会变慢
            if (i % 10000 == 0) {
                demoService.saveBatch(demoList);
                log.warn("i=={}, 用时=={}s", i, timeInterval.intervalSecond());
                demoList.clear();
            }
        }
        //持久化。
        demoService.saveBatch(demoList);
        log.warn("总用时=={}s", timeInterval.intervalSecond());
        return demoService.count();
    }


    @GetMapping("/resetDbData")
    void resetDbData() {
        MyDbUtil.resetData(ds, "db_sql/lishuoboy-mysql-index.sql");
    }

}
